package top.jacktgq.hsp.netty.buf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;

/**
 * @Author CandyWall
 * @Date 2020/11/12--18:46
 * @Description 测试使用ByteBuf
 */
public class NettyByteBuf02 {
    public static void main(String[] args) {
        //创建ByteBuf
        ByteBuf byteBuf = Unpooled.copiedBuffer("早安，打工人", CharsetUtil.UTF_8);

        //使用相关的方法
        if (byteBuf.hasArray()) {
            byte[] bytes = byteBuf.array();
            System.out.println(new String(bytes, Charset.forName("utf-8")));
            System.out.println("byteBuf.arrayOffset() = " + byteBuf.arrayOffset());
            System.out.println("byteBuf.readerIndex() = " + byteBuf.readerIndex());
            System.out.println("byteBuf.writerIndex() = " + byteBuf.writerIndex());
            System.out.println("byteBuf.capacity() = " + byteBuf.capacity());
            System.out.println("byteBuf.readableBytes() = " + byteBuf.readableBytes());

            System.out.println(byteBuf.readByte());

            System.out.println("byteBuf.readableBytes() = " + byteBuf.readableBytes());

            //使用for循环取出各个字节
            System.out.print("byteBuf.getByte(i) = ");
            for (int i = 0; i < byteBuf.readableBytes(); i++) {
                System.out.print(byteBuf.getByte(i) + " ");
            }
            System.out.println();
            System.out.println(byteBuf.getCharSequence(0, 6, CharsetUtil.UTF_8));
        }
    }
}
